#include "accountloginner.h"
#include "network/networkhttprequest.h"
#include "network/networkmanager.h"
#include "network/networkresponse.h"
#include "accountloginrequest.h"
#include "accountloginresponse.h"
#include "account/accountmanager.h"
#include "accountloginrequest.h"

#include <QDebug>


namespace Account {

Loginner *Loginner::m_instance = NULL;

Loginner::Loginner(QObject *parent) :
    QObject(parent)
{

}

bool Loginner::login(QString userName, QString pass)
{
    LoginRequest *loginRequest = new LoginRequest(userName, pass, this);
    connect(loginRequest, &LoginRequest::responded, this, &Loginner::onLoginResponsed);
    Network::Manager *manager = Network::Manager::instance();
    if (!manager->post(loginRequest)) {
        delete loginRequest;
        loginRequest = NULL;
        return false;
    }

    return true;
}

void Loginner::logout()
{
    emit logouted();
}

void Loginner::onLoginResponsed(Network::HttpRequest *request)
{
    const Network::HttpRequest &constRequest = *request;
    const Network::Response &response = constRequest.response();
    if (response.type() != Network::Response::Login)
        return;

    const LoginResponse &loginResponse = (const LoginResponse &)response;
    if(response.error() == Network::Response::None) {
        Account::Manager::instance()->init(loginResponse);
        emit logined(true, loginResponse.message(), loginResponse.sessionKey());
    } else {
        emit logined(false, loginResponse.message(), "" );
    }

    request->deleteLater();
}

Loginner* Loginner::instance(QObject *parent)
{
    if(m_instance == NULL)
        m_instance = new Loginner(parent);
    return m_instance;
}

} // namespace Account
